﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace WordsGame
{
    [Serializable]
    public class Standings : IEquatable<Standings>
    {
        [XmlArray]
        public List<Player> Players { get; set; }

        public Standings()
        {
            Players = new List<Player>();
        }

        public void Change(string name, int delta)
        {
            var player = Players.Find(
                p => string.Compare(p.Name, name, StringComparison.OrdinalIgnoreCase) == 0);
            if (player == null)
            {
                player = new Player(name);
                Players.Add(player);
            }

            player.Score += delta;
            Players.Sort((player1, player2) => -player1.CompareTo(player2));
        }

        public bool Equals(Standings other)
        {
            if (Players.Count != other.Players.Count)
            {
                return false;
            }

            for (int i = 0; i < Players.Count; ++i)
            {
                var name = Players[i].Name;
                var otherName = other.Players[i].Name;
                if (string.Compare(name, otherName, StringComparison.OrdinalIgnoreCase) != 0 ||
                    Players[i].Score != other.Players[i].Score)
                {
                    return false;
                }
            }

            return true;
        }
    }
}
